//
//  EmoticonController.swift
//  表情键盘
//
//  Created by 耐克了解了 on 12/4/17.
//  Copyright © 2017年 耐克了解了. All rights reserved.
//

import UIKit

fileprivate let emoticonCell = "emoticonCell"

class EmoticonController: UIViewController {
 
    //MARK:-定义属性
    var emoticonCallBack : (_ emoticon : Emoticon) ->()
    
    //MARK:-懒加载
    lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EMoyiconCollectionViewLayout())

    lazy var toolBar : UIToolbar = UIToolbar()
    
    lazy var manager : EmoticonManager = EmoticonManager()
    
     //MARK:-自定义构造函数
    //___________----------************
    init(emoticonCallBack : @escaping (_ emoticon : Emoticon) ->()){
        
        self.emoticonCallBack = emoticonCallBack
        
        super.init(nibName: nil, bundle: nil)
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //___________----------************
    //MARK:-系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
      
        setupUI()
        
        
    }

}

//MARK:-设置UI界面
extension EmoticonController{
  fileprivate  func setupUI(){
    
    //添加子控件
    view.addSubview(collectionView)
    view.addSubview(toolBar)
    
    collectionView.backgroundColor = UIColor.lightGray
    toolBar.backgroundColor = UIColor.lightGray
    
    
    //设置子控件的frame
    //VFL
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    
    toolBar.translatesAutoresizingMaskIntoConstraints = false
    
    let views = ["toolBar" : toolBar , "collectionView" : collectionView] as [String : Any]
    
    var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[toolBar]-0-|", options: [], metrics: nil, views: views)
    cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-[toolBar]-0-|", options: [.alignAllLeft , .alignAllRight], metrics: nil
        , views: views)
    view.addConstraints(cons)
    
    //准备collectionView
    prepareForCollectionView()
    
    //准备ToolBar
    prepareForToolBar()
    
    }
    
    fileprivate func prepareForCollectionView(){
        
        //注册cell和设置数据源
        collectionView.register(EmoticonViewCell.self, forCellWithReuseIdentifier: emoticonCell)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        
    }
    
    fileprivate func prepareForToolBar(){
        
        //定义toolBar中的title
        let titles = ["最近","默认","emoji","浪小花"]
        
        
        //遍历标题创建item
        var index = 0
        var tempItems = [UIBarButtonItem]()
        
        for title in titles {
            
            let item  = UIBarButtonItem(title: title, style: .plain, target: self, action:#selector(itemClick(item:)))
            item.tag = index
            index+=1
            
            tempItems.append(item)
            tempItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            
        }
        
        //设置tooBar的items数组
        tempItems.removeLast()
        toolBar.items = tempItems
        
    }
    
    @objc fileprivate func itemClick(item: UIBarButtonItem){
        
        //获取点击的item的tag值
        let tag = item.tag
        
        //根据Tag获取当前的组
        let indexPath = IndexPath(item: 0, section: tag)//(forItem: 0 ,inSection: tag)
        
        //滚到到对应的位置
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
        
    }
    
}

// MARK: -UICollectionViewDataSource
extension EmoticonController : UICollectionViewDataSource ,UICollectionViewDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return manager.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let package = manager.packages[section]
        
        return package.emoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: emoticonCell, for: indexPath) as! EmoticonViewCell
        
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.purple : UIColor.green
        //给cell设置数据
        let pack = manager.packages[indexPath.section]
        let emoticon = pack.emoticons[indexPath.item]
        cell.emoticonModel = emoticon
        
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        //取出点击的表情
        let package = manager.packages[indexPath.section]
        
        let emoticon = package.emoticons[indexPath.item]
        
        
        //将点击的表情插入到最近分组中
        insertRecentllyEmoticon(emoticon: emoticon)
        
        //将表情回调给外界控制器
        emoticonCallBack(emoticon)
        
    }
    
    fileprivate func insertRecentllyEmoticon(emoticon : Emoticon)
    {
        //如果是空白表情和删除表情不需要插入
        
        if emoticon.isRemove || emoticon.isEmpty {
            return
        }
        
        //删除一个表情
        if manager.packages.first!.emoticons.contains(emoticon) {//该表情已存在
            
            let index = (manager.packages.first?.emoticons.index(of: emoticon))!
            
            
            manager.packages.first?.emoticons.remove(at: index)
            
        }else{
            
            manager.packages.first?.emoticons.remove(at: 19)
        }
        
        //将emoticon插入到最近分组中
        manager.packages.first?.emoticons.insert(emoticon, at: 0)
        
    }

}

class EMoyiconCollectionViewLayout : UICollectionViewFlowLayout {
    
    override func prepare(){
        super.prepare()
        
        //计算item的宽度和高度
        let itemWH = UIScreen.main.bounds.size.width / 7
        itemSize = CGSize(width: itemWH, height: itemWH)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        collectionView?.isPagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        let insertMargin = ((collectionView?.bounds.height)! - 3 * itemWH) * 0.5
        
        collectionView?.contentInset = UIEdgeInsetsMake(insertMargin, 0, insertMargin, 0)
    }
}
